package cn.huhaoran.yaoyaolingxian.config;


import cn.huhaoran.yaoyaolingxian.ui.NewPageAndeViewModelContainer;
import cn.huhaoran.yaoyaolingxian.util.YaoYaoLingXianUtils;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 新建页面的配置
 *
 * @author huhaoran
 * @date 2024-07-13
 */
public class NewPageAndViewModelConfig implements Configurable {

    private final Project project;
    private final JComponent mainPanel;
    private final TextFieldWithBrowseButton jsonPath;
    private final TextFieldWithBrowseButton enumPath;
    NewPageAndeViewModelContainer newPageAndeViewModelContainer;
    NewPageAndViewModel newPageAndViewModel;
    private JComboBox<String> enumName;
    private HashMap<String,JCheckBox> textToJCheckBoxMap=new HashMap<String,JCheckBox>();
    public Map<String, List<String>> enumNameMap;

    public NewPageAndViewModelConfig(Project project) {
        this.project = project;
        newPageAndeViewModelContainer = new NewPageAndeViewModelContainer();
        newPageAndViewModel = NewPageAndViewModel.getInstance(project);
        mainPanel = newPageAndeViewModelContainer.getMainPanel();
        jsonPath = newPageAndeViewModelContainer.getJsonPath();
        enumPath = newPageAndeViewModelContainer.getEnumPath();
        enumName = newPageAndeViewModelContainer.getEnumName();
        enumNameMap = newPageAndeViewModelContainer.getEnumNameMap();
        // 用反射构建TextTO对象 testToJCheckBoxMap
        for (java.lang.reflect.Field field : newPageAndeViewModelContainer.getClass().getDeclaredFields()) {
            if (field.getType().equals(JCheckBox.class)) {
                try {
                    JCheckBox jCheckBox = (JCheckBox) field.get(newPageAndeViewModelContainer);
                    textToJCheckBoxMap.put(jCheckBox.getText(), jCheckBox);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        // 将持久化的值设置到UI
        setUIbyModel();
        this.newPageAndeViewModelContainer = newPageAndeViewModelContainer;
    }

    /**
     * setUIbyModel 从持久化数据中读取值并设置UI界面
     * @author huhaoran
     * @date 2024/7/16
     *
     * @param
     * @return void
     */
    private void setUIbyModel() {
        // 路由json文件路径
        jsonPath.setText(newPageAndViewModel.getJsonPath());
        // 页面名称枚举路径
        enumPath.setText(newPageAndViewModel.getEnumPath());
        // 设置枚举名下拉框内容，已经枚举名称
        if(StringUtil.isNotEmpty(newPageAndViewModel.getEnumName())){
            // todo 还需要添加是否是新加枚举类的判断，目前没有添加
            //enumName.setSelectedItem(newPageAndViewModel.getEnumName());
            try {
                Map<String, List<String>> stringListMap = YaoYaoLingXianUtils.parseFileContent(newPageAndViewModel.getEnumPath());
                enumName.removeAllItems();
                stringListMap.keySet().forEach((item)-> enumName.addItem(item));
                if(enumName.getItemCount()>0){
                    enumName.setSelectedItem(newPageAndViewModel.getEnumName());
                }
            } catch (IOException e) {
                Notifications.Bus.notify(new Notification("Print", "出现错误",
                        "在解析枚举文件时发生错误："+e.getMessage() , NotificationType.WARNING), project);
            }
        }
        // 读取和设置多选框的状态
        HashMap<String, Boolean> checkBoxMapData = newPageAndViewModel.getCheckBoxMap();
        if (checkBoxMapData != null) {
            // 通过反射来设置newPageAndeViewModelContainer的属性值
            for (String key : checkBoxMapData.keySet()) {
                textToJCheckBoxMap.get(key).setSelected(checkBoxMapData.get(key));
            }
        }
    }

    @Override
    public void reset() {
        Configurable.super.reset();
        setUIbyModel();
    }

    @Override
    public String getDisplayName() {
        return "遥遥领先";
    }

    @Override
    public @Nullable JComponent createComponent() {
        return mainPanel;
    }

    @Override
    public boolean isModified() {
        NewPageAndViewModel instance = NewPageAndViewModel.getInstance(project);
        if (!YaoYaoLingXianUtils.areStringsEqual(instance.getJsonPath(), newPageAndeViewModelContainer.jsonPath.getText()))
            return true;
        if (!YaoYaoLingXianUtils.areStringsEqual(instance.getEnumPath(), newPageAndeViewModelContainer.enumPath.getText()))
            return true;
        if (newPageAndeViewModelContainer.enumName.getItemCount() == 0) {
            if (StringUtil.isNotEmpty(instance.getEnumName())) {
                return true;
            }
        } else {
            if (!YaoYaoLingXianUtils.areStringsEqual(instance.getEnumName(), newPageAndeViewModelContainer.enumName.getSelectedItem().toString()))
                return true;
        }
        // 通过反射获取newPageAndeViewModelContainer 的所有JComboBox的text：选中与否的map
        HashMap<String, Boolean> nowCheckBoxMap = new HashMap<>();
        for (java.lang.reflect.Field field : NewPageAndeViewModelContainer.class.getDeclaredFields()) {
            if (field.getType().equals(JCheckBox.class)) {
                try {
                    JCheckBox jCheckBox = (JCheckBox) field.get(this.newPageAndeViewModelContainer);
                    nowCheckBoxMap.put(jCheckBox.getText(), jCheckBox.isSelected());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        // 持久化的值
        HashMap<String, Boolean> saveCheckBoxMapData = instance.getCheckBoxMap();
        AtomicInteger noEqualNum = new AtomicInteger();
        nowCheckBoxMap.forEach((key, value) -> {
            if (saveCheckBoxMapData.containsKey(key)) {
                if (!Objects.equals(saveCheckBoxMapData.get(key), value)) {
                    noEqualNum.getAndIncrement();
                }
            } else {
                if (Boolean.TRUE.equals(value)) {
                    noEqualNum.getAndIncrement();
                }
            }
        });
        if (noEqualNum.getAndIncrement() != 0) return true;
        return false;
    }

    /**
     * apply 保存设置的值
     *
     * @param
     * @return void
     * @author huhaoran
     * @date 2024/7/15
     */
    @Override
    public void apply() {
        NewPageAndViewModel instance = NewPageAndViewModel.getInstance(project);
        instance.setJsonPath(jsonPath.getText());
        instance.setEnumPath(enumPath.getText());
        if (enumName.getSelectedItem() == null) {
            instance.setEnumName("");
        } else {
            instance.setEnumName(enumName.getSelectedItem().toString());
        }
        // 获取NewPageAndViewModel对象的所有JCheckBox类型的属性，并将其转换城一个HashMap<String,Boolean>，其key是该属性的text值，value是该属性的选中状态
        HashMap<String, Boolean> checkBoxMap = new HashMap<>();
        for (java.lang.reflect.Field field : NewPageAndeViewModelContainer.class.getDeclaredFields()) {
            if (field.getType().equals(JCheckBox.class)) {
                try {
                    JCheckBox jCheckBox = (JCheckBox) field.get(this.newPageAndeViewModelContainer);
                    checkBoxMap.put(jCheckBox.getText(), jCheckBox.isSelected());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        instance.setCheckBoxMap(checkBoxMap);
    }
}
